from werkzeug.utils import secure_filename
from log_util import *
from flask import *

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello"

@app.route("/<username>/<int:userid>")
def get_user(username,userid):
    logger.info(f"{userid}")
    return f"名字{username},学号{userid}"

@app.route("/login",methods=["POST","GET"])
def login():
    if request.method == "POST":
        request_json = request.json
        print(request_json)
        name = request_json.get("name")
        age = request_json.get("age")
        return f"POST:name: {name}, age: {age}"
    else:
        request_args = request.args
        print(request_args)
        name = request_args.get("name")
        age = request_args.get("age")
        return f"GET:name: {name}, age: {age}"

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    # 获取请求 URL
    r_url = request.url
    # 获取请求域名
    r_host = request.host
    # 获取请求头信息
    r_headers = request.headers
    # 获取请求方法
    r_method = request.method
    print(r_url, r_host, r_headers, r_method)
    # 获取文件请求体
    r_file = request.files
    # 判断请求方法为 POST
    if r_method == 'POST':
        # 判断请求头中包含 My-Header 字段并且值为 hogwarts
        if r_headers.get('My-Header') == "hogwarts":
            # 保存文件
            f = r_file.get("file")
            f.save('./uploads/' + secure_filename(f.filename))
            return f'File {f.filename} is saved! URL is {r_url}, host is {r_host}'
        return f"My-Header is missing!"
    return f"Method is wrong!"






@app.route("/html")
def get_html():
    # 调用render_template方法，传入html 文件的名称。
    # 注意html文件必须在 templates 目录下
    return render_template("demo.html")

@app.route("/cookie")
def index():
    resp = make_response(render_template("demo.html"))
    # 设置cookie
    resp.set_cookie("username", "the username")
    # 设置响应头信息
    resp.headers["hogwarts"] = "Hary"
    return resp

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5050)
